package com.yunquan.ohana.http.body

import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.BufferedSink
import java.io.File
import java.io.FileInputStream

class ProgressRequestBody(
    private val file: File,
    private val onProgressUpdate: (uploaded: Long, total: Long) -> Unit
) : RequestBody() {

    override fun contentType(): MediaType {
        return "multipart/form-data".toMediaType()
    }

    override fun contentLength(): Long {
        return file.length()
    }

    override fun writeTo(sink: BufferedSink) {
        val buffer = ByteArray(2048)
        val inputStream = FileInputStream(file)
        inputStream.use { input ->
            var uploaded = 0L
            var read: Int
            while (input.read(buffer).also { read = it } != -1) {
                uploaded += read
                sink.write(buffer, 0, read)
                onProgressUpdate(uploaded, contentLength())
            }
        }
    }
}